package cn.ai.shoes.core.utils;

import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.common.pojo.entity.CommonResult;
import cn.ai.shoes.core.pojo.entity.MyUser;
import cn.ai.shoes.core.service.UserService;
import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.io.IOException;
import java.util.Map;

public class AuthenticationUtils {
    public interface LoginTypeProcessor {
        void process(Map<String, Object> result, UserDetails userDetails);
    }

    // 预定义的登录类型处理器
    public static final LoginTypeProcessor SMS_LOGIN_PROCESSOR = (result, userDetails) -> {
        result.put("loginType", "SMS");
        // 可以添加更多SMS登录特有的逻辑
    };

    public static final LoginTypeProcessor PASSWORD_LOGIN_PROCESSOR = (result, userDetails) -> {
        result.put("loginType", "PASSWORD");
        // 可以添加更多密码登录特有的逻辑
    };

    // 默认处理器
    public static final LoginTypeProcessor DEFAULT_PROCESSOR = (result, userDetails) -> {
        result.put("loginType", "DEFAULT");
    };

    public static String response(
            UserDetails userDetails,
            UserService userService,
            LoginTypeProcessor loginProcessor) throws IOException {
        // 根据用户名称查询用户信息
        MyUser myUser = userService.getOne(new QueryWrapper<MyUser>().eq("username", userDetails.getUsername()));
        myUser.setPassword(null);
        // myUser.getRole()转小写
        myUser.setRole(myUser.getRole().toLowerCase());
        myUser.setDeleted(null);

        Map<String, Object> result = BeanUtil.beanToMap(myUser);

        String token = JwtUtils.generateJwt(userDetails);
        // 生成Authorization
        String authorization = JwtUtils.getTokenPrefix() + " " + token;
        // 将token存储到map
        // 短信登录特有的处理逻辑
        // 使用函数式对象处理登录类型特定逻辑
        if (loginProcessor != null) {
            loginProcessor.process(result, userDetails);
        } else {
            DEFAULT_PROCESSOR.process(result, userDetails);
        }
        result.put("Authorization", authorization);
        // 将result对象转换为json字符串
        String json = JSON.toJSONString(CommonResult.success(result));
        return json;
    }

    @NotNull
    public static UserDetails createUserDetails(String username, String phone, UserService userService) throws ServiceException{
        MyUser myUser = null;
        if (phone == null) {
            myUser = userService.selectOne(username);
        }else {
            myUser = userService.selectOneByPhone(phone);
        }
        if (myUser == null) {
            throw new ServiceException("用户不存在");
        } else {
            return myUser; // 直接返回MyUser对象
        }
    }
}

